package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.User;
import com.bwie.service.UserService;
import com.bwie.mapper.UserMapper;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import com.bwie.vo.UserVo;
import com.google.j2objc.annotations.Weak;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

/**
* @author 36167
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-03-19 09:41:36
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public R login(LoginInfoVo loginInfoVo) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,loginInfoVo.getUserName());
        wrapper.eq(User::getPassword,loginInfoVo.getUserPass());
        User one = getOne(wrapper);

        if (one==null){
            return R.ERROR(500,"用户不存在");
        }

        //长期token
        String token = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS256, "123456").claim("uid", one.getUid()).compact();
        //短期token
        String reftoken = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() + 7200 * 1000))
                .signWith(SignatureAlgorithm.HS256, "123456").claim("uid", one.getUid()).compact();
        stringRedisTemplate.opsForValue().set(reftoken,token);

        UserVo userVo = new UserVo();
        userVo.setRefToken(reftoken);
        userVo.setRefTokenTime(System.currentTimeMillis()+7200+1000);
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",one);
        map.put("userVo",userVo);
        return R.OK(map);
    }

    @Override
    public R getuser(Integer id) {
        User byId = getById(id);
        return R.OK(byId);
    }
}




